package com.example.fmradio;
import ca.gc.crc.libfmrds.FMinterface; 
import android.media.AudioManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {
	
	private FMinterface CRC_FMRDS_Library = new FMinterface();
	private AudioManager aManager;
	private int currentFreq;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((Button)findViewById(R.id.button1)).setOnClickListener(this);
    }
    public void onStart(){
    	super.onStart();
    	aManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE); //Put this in the doc? 	
    }
    public void onClick(View v) {
    	switch(v.getId()) {
    	case R.id.button1:
    		String tmp = ((EditText)findViewById(R.id.editText1)).getText().toString();
    		currentFreq = Integer.parseInt(tmp.trim());
    		
    		if (CRC_FMRDS_Library.radioIsSupported()) {
    		    ((TextView)findViewById(R.id.textView2)).setText(""+currentFreq);            
    		    CRC_FMRDS_Library.openRadio(aManager);
    		    CRC_FMRDS_Library.setBand(CRC_FMRDS_Library.BAND_87500_108000_kHz);
    		    CRC_FMRDS_Library.setSpacing(CRC_FMRDS_Library.CHAN_SPACING_100_kHz);
    		    CRC_FMRDS_Library.setEmphasis(CRC_FMRDS_Library.DE_TIME_CONSTANT_50);
    		    CRC_FMRDS_Library.setChannel(currentFreq);
    		    int i = 0;
    		    while (i < 20){
    		        try {
    		            Thread.sleep(250);
    		        } catch (InterruptedException e) {
    		        }
    		        CRC_FMRDS_Library.processRDS();
    		        CRC_FMRDS_Library.syncMediaVolume(aManager);
    		        i++;
    		    }
    		    String PI = Integer.toHexString(CRC_FMRDS_Library.getPI());
    		    String PS = CRC_FMRDS_Library.getPS();
    		    String RT = CRC_FMRDS_Library.getRT();
    		    ((TextView)findViewById(R.id.textView2)).setText(RT);            
    		    CRC_FMRDS_Library.closeRadio(aManager); 
    		} else {
	    		Toast.makeText(this.getApplicationContext(), "This phone is not supported by the CRC FM-RDS Library for Android", 1);
	    		((TextView)findViewById(R.id.textView2)).setText("This phone is not supported by the CRC FM-RDS Library for Android");
	    	}
    		break;
		default:
			break;
    	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
